/*
 * @Project Name: spring-boot
 * @File Name: UserService
 * @Package Name: com.hhly.spring.boot.cache
 * @Date: 2017/12/13 17:52
 * @Creator: linshixing-1199
 * @line------------------------------
 * @修改人:
 * @修改时间:
 * @修改内容:
 */

package com.sm.shoplook.service.system.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sm.shoplook.constant.ResultMessage;
import com.sm.shoplook.dao.mapper.system.*;
import com.sm.shoplook.domain.system.*;
import com.sm.shoplook.service.system.RoleService;
import com.sm.shoplook.shiro.Principal;
import com.sm.shoplook.vo.base.ApiException;
import com.sm.shoplook.vo.base.ApiResult;
import com.sm.shoplook.vo.system.role.RolePageSearchReqVo;
import com.sm.shoplook.vo.system.user.resp.UserRoleRespVo;

/**
 * @author chenpy-1072
 * @desc UserService
 * @date 2017/12/13 17:52
 * @see
 */
@Service
public class RoleServiceImpl implements RoleService {

	private static final Logger LOGGER = LoggerFactory.getLogger(RoleServiceImpl.class);
	@Autowired
	private RoleMapper roleMapper;
	@Autowired
	private RolePermissionMapper rolePermissionMapper;
	@Autowired
	private RoleMenuMapper roleMenuMapper;
	@Autowired
	private PermissionMapper permissionMapper;
	@Autowired
	private UserMapper userMapper;

	@Override
	public ApiResult<PageInfo<Role>> selectRoleListPage(RolePageSearchReqVo rolePageSearchReqVo) {
		PageHelper.startPage(rolePageSearchReqVo.getOffset(), rolePageSearchReqVo.getPageSize());
		List<Role> roles = roleMapper.selectRoleListPage(rolePageSearchReqVo);
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, new PageInfo<>(roles));
	}

	@Override
	public ApiResult<Role> selectRoleById(Integer roleId) {
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, roleMapper.selectByPrimaryKey(roleId));
	}

	@Override
	public ApiResult deleteRoles(String[] idList) throws ApiException {
		int i = roleMapper.deleteRoles(idList);
		if (i < 1) {
			throw new ApiException();
		}
		return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
	}

	@Override
	public ApiResult saveRole(Role role) throws ApiException {
		User user = new User();
		user.setUpdateTime(new Date());
		Principal principal = (Principal) SecurityUtils.getSubject().getPrincipal();
		int i;
		if (role.getId() == null) {
			// 判断角色是否已存在
			Role r = new Role();
			r.setRoleName(role.getRoleName());
			List<Role> roles = roleMapper.select(r);
			if (CollectionUtils.isNotEmpty(roles)) {
				return new ApiResult(ResultMessage.ROLE_NAME_EXISTS);
			}
			role.setRoleCode("ROLE_" + System.currentTimeMillis());
			role.setCreateTime(new Date());
			i = roleMapper.insertSelective(role);
		} else {
			// 判断角色是否已存在
			Role r = new Role();
			r.setRoleName(role.getRoleName());
			List<Role> roles = roleMapper.select(r);
			if (CollectionUtils.isNotEmpty(roles) && !role.getId().equals(roles.get(0).getId())) {
				return new ApiResult(ResultMessage.ROLE_NAME_EXISTS);
			}
			role.setUpdateTime(new Date());
			role.setUpdateUser(principal.getUserName());
			i = roleMapper.updateByPrimaryKeySelective(role);
		}
		if (i < 1) {
			throw new ApiException();
		}
		return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
	}

	@Override
	public ApiResult<List<String>> selectRoleMenuPermissions(String roleCode) {
		List<Permission> permissions = permissionMapper.selectPermissionsByRoleCode(roleCode);
		List<String> result = new ArrayList<>();
		if (CollectionUtils.isNotEmpty(permissions)) {
			List<String> permissionCodes = permissions.stream().map(permission -> permission.getPermissionCode())
					.collect(Collectors.toList());
			result.addAll(permissionCodes);
		}
		List<String> menuCodes = roleMenuMapper.selectRoleMenuCodes(roleCode);
		if (CollectionUtils.isNotEmpty(menuCodes)) {
			result.addAll(menuCodes);
		}
		return new ApiResult<>(ResultMessage.RESULT_SUCCESS_1, result);
	}

	@Override
	public ApiResult saveRolePermission(String menuCodes, String permissionCodes, String roleCode) throws ApiException {
		// 1、删除角色所有关联的权限
		RolePermission rp = new RolePermission();
		rp.setRoleCode(roleCode);
		rolePermissionMapper.delete(rp);
		// 2、删除角色所有关联的菜单
		RoleMenu roleMenuParam = new RoleMenu();
		roleMenuParam.setRoleCode(roleCode);
		roleMenuMapper.delete(roleMenuParam);
		// 3、添加角色菜单
		if (StringUtils.isNotEmpty(menuCodes)) {
			List<RoleMenu> roleMenus = new ArrayList<>();
			String[] menuCodeArray = menuCodes.split(",");
			for (String menuCode : menuCodeArray) {
				RoleMenu roleMenu = new RoleMenu();
				roleMenu.setRoleCode(roleCode);
				roleMenu.setMenuCode(menuCode);
				roleMenus.add(roleMenu);
			}
			roleMenuMapper.batchInsert(roleMenus);
		}
		// 4、添加角色权限
		if (StringUtils.isNotEmpty(permissionCodes)) {
			List<RolePermission> rolePermissions = new ArrayList<>();
			String[] permissionCodeArray = permissionCodes.split(",");
			for (String permissionCode : permissionCodeArray) {
				RolePermission rolePermission = new RolePermission();
				rolePermission.setRoleCode(roleCode);
				rolePermission.setPermissionCode(permissionCode);
				rolePermissions.add(rolePermission);
			}
			rolePermissionMapper.batchInsert(rolePermissions);
		}
		// 判断当前登录用户是否为当前修改的角色
		Object o = SecurityUtils.getSubject().getPrincipal();
		if (o == null) {
			return new ApiResult(ResultMessage.LOGOUT_LOGIN);
		}
		Principal principal = (Principal) o;
		UserRoleRespVo userRoleRespVo = userMapper.selectUserRoleByUserId(principal.getUserId());
		if (StringUtils.isNotEmpty(userRoleRespVo.getRoleCode()) && roleCode.equals(userRoleRespVo.getRoleCode())) {
			return new ApiResult(ResultMessage.LOGOUT_LOGIN);
		}
		return new ApiResult(ResultMessage.RESULT_SUCCESS_1);
	}
}
